<%@ page import="com.example.util.DBUtil" %>
<%@ page import="com.example.domain.User" %>
<%@ page import="java.sql.*" %>
<%@ page contentType="text/plain;charset=UTF-8" language="java" %>
<%
    // 检查用户是否已登录
    User currentUser = (User) session.getAttribute("user");
    if (currentUser == null) {
        response.getWriter().print("未登录");
        return;
    }
    
    Connection conn = null;
    try {
        int productId = Integer.parseInt(request.getParameter("productId"));
        int quantity = 1; // 默认数量为1
        
        // 如果提供了数量参数，则使用该数量
        String quantityParam = request.getParameter("quantity");
        if (quantityParam != null && !quantityParam.isEmpty()) {
            quantity = Integer.parseInt(quantityParam);
        }
        
        if (quantity < 1) {
            response.getWriter().print("数量不能小于1");
            return;
        }
        
        conn = DBUtil.getConnection();
        
        // 检查商品是否存在并获取价格
        String productSql = "SELECT price, sale_price FROM tb_product WHERE id = ?";
        PreparedStatement productStmt = conn.prepareStatement(productSql);
        productStmt.setInt(1, productId);
        ResultSet productRs = productStmt.executeQuery();
        
        if (!productRs.next()) {
            response.getWriter().print("商品不存在");
            return;
        }
        
        // 获取产品价格信息
        double price = productRs.getDouble("price");
        double salePrice = productRs.getDouble("sale_price");
        double productPrice = (salePrice > 0) ? salePrice : price;
        
        // 检查商品是否已在购物车中
        String checkSql = "SELECT id, sale_num FROM tb_cart WHERE member_id = ? AND product_id = ?";
        PreparedStatement checkStmt = conn.prepareStatement(checkSql);
        checkStmt.setInt(1, currentUser.getId());
        checkStmt.setInt(2, productId);
        ResultSet rs = checkStmt.executeQuery();
        
        if (rs.next()) {
            // 如果商品已在购物车中，则增加数量
            int cartId = rs.getInt("id");
            int currentQuantity = rs.getInt("sale_num");
            
            String updateSql = "UPDATE tb_cart SET sale_num = ?, sale_price = ?, sale_money = ? WHERE id = ?";
            PreparedStatement updateStmt = conn.prepareStatement(updateSql);
            updateStmt.setInt(1, currentQuantity + quantity);
            updateStmt.setDouble(2, productPrice);
            updateStmt.setDouble(3, productPrice * (currentQuantity + quantity));
            updateStmt.setInt(4, cartId);
            updateStmt.executeUpdate();
            updateStmt.close();
        } else {
            // 如果商品不在购物车中，则添加新记录
            String insertSql = "INSERT INTO tb_cart (member_id, product_id, sale_num, sale_price, sale_money) VALUES (?, ?, ?, ?, ?)";
            PreparedStatement insertStmt = conn.prepareStatement(insertSql);
            insertStmt.setInt(1, currentUser.getId());
            insertStmt.setInt(2, productId);
            insertStmt.setInt(3, quantity);
            insertStmt.setDouble(4, productPrice);
            insertStmt.setDouble(5, productPrice * quantity);
            insertStmt.executeUpdate();
            insertStmt.close();
        }
        
        productStmt.close();
        checkStmt.close();
        
        response.getWriter().print("success");
        return;
    } catch (Exception e) {
        response.getWriter().print("error: " + e.getMessage());
    } finally {
        // 关闭数据库连接
        try {
            if (conn != null) conn.close();
        } catch (Exception e) {
            // 忽略关闭连接的异常
        }
    }
%>